using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using System.IO;
using FileDownloadServer;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Win32.Dialogs;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
using Tests.Properties;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using System.Linq;
using FluentAssertions;
using ArtOfTest.Common.Win32;
using System.Diagnostics;

namespace Tests
{
	class FileDownloadTester : IDisposable
	{
		public FileDownloadTester(Directory serverApplicationPath)
		{
			WebApplicationLauncher serverLauncher = new WebApplicationLauncher(serverApplicationPath);
			var startServer = serverLauncher.Start();
			
			chromeLauncher = ChromeLauncherManager.SetUp().Result;
			var launchChrome = chromeLauncher.Launch();
			
			Task.WaitAll(startServer, launchChrome);
			server = startServer.Result;
			chrome = launchChrome.Result;

			var serverAddress = server.Address;
			client = new FileDownloadServerClient(serverAddress);
		}

		public void Dispose()
		{
			server.Dispose();
			chromeLauncher.Dispose();
		}

		private readonly WebApplication server;
		private readonly ChromeLauncher chromeLauncher;

		public async Task<TestResult> Test(string fileName, FileDownloadProperties properties, IPageMatcher matcher)
		{
			var downloadAddress = await client.ConfigureDownload(fileName, properties);
			var htmlSource = await chrome.NavigateTo(downloadAddress);
			if (htmlSource == null)
				return TestResult.DidntDisplay;

			var page = new Page(downloadAddress, htmlSource);
			var hasCorrectPageContent = matcher.Matches(page);
			return hasCorrectPageContent ? TestResult.Displayed : TestResult.DisplayedIncorrectly;
		}

		private readonly FileDownloadServerClient client;
		private readonly Chrome chrome;
	}
}